package com.syp.auth.web.controller;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.syp.auth.common.Constants;
import com.syp.auth.domain.ProcessResult;
import com.syp.auth.domain.vo.ResourceVo;
import com.syp.auth.domain.vo.UserVo;
import com.syp.auth.domain.vo.easyui.DataGrid;
import com.syp.auth.domain.vo.easyui.Json;
import com.syp.auth.export.annotation.SecurityNone;
import com.syp.auth.export.annotation.SessionNone;
import com.syp.auth.export.common.GeneralUserVo;
import com.syp.auth.export.common.GorgeousParameters;
import com.syp.auth.export.common.TokenCooikeMaster;
import com.syp.auth.export.resource.AuthorizeResourceI;
import com.syp.auth.export.util.CurrentUserHolder;
import com.syp.auth.service.base.UserServiceI;

@Controller
@RequestMapping("/sys/user")
public class UserController {
	
	private static final Logger log = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserServiceI userService = null;
	@Autowired
	private AuthorizeResourceI authorizeResource = null;

	/**
	 * 主页面跳转action
	 * 
	 * @return
	 */
	@RequestMapping("/main")
	public ModelAndView mainPage(@CookieValue(GorgeousParameters.AUTH_COOKIE_NAME) String sid) {
		ModelAndView mv = new ModelAndView("sys/user/user");
		GeneralUserVo guser = CurrentUserHolder.get();
		if (guser == null) {
			guser = this.authorizeResource.cuser(sid);
		}
		List<String> permitUrlList = guser.getPermitUrlList();
		mv.addObject("permitUrlList", permitUrlList);
		return mv;
	}

	/**
	 * 新增页面跳转action
	 * 
	 * @return
	 */
	@RequestMapping("/bindPage")
	public String bindPage() {
		return "sys/user/userBind";
	}

	/**
	 * 新增页面跳转action
	 * 
	 * @return
	 */
	@RequestMapping("/addPage")
	public ModelAndView addPage() {
		ModelAndView mv = new ModelAndView("sys/user/userAdd");
		return mv;
	}

	/**
	 * 编辑页面跳转action
	 * 
	 * @return
	 */
	@RequestMapping("/editPage")
	public ModelAndView editPage(String uid) {
		ModelAndView mv = new ModelAndView("sys/user/userEdit");
		boolean isSuperMan = false;
		if (uid != null && uid.equals(Constants.SUPER_MAN_NO.toString())) {
			isSuperMan = true;
		}
		mv.addObject("isSuperMan", isSuperMan);
		return mv;
	}

	/**
	 * 查看页面跳转action
	 * 
	 * @return
	 */
	@RequestMapping("/showPage")
	public String showPage() {
		return "sys/user/userShow";
	}

	@RequestMapping("/grantPage")
	public String grantPage() {
		return "sys/user/userGrant";
	}

	@RequestMapping("/grantBatchPage")
	public String grantBatchPage() {
		return "sys/user/userBatchGrant";
	}

	@RequestMapping("/userInfo")
	public String userInfo() {
		return "sys/user/userInfo";
	}

	@RequestMapping("/add")
	@ResponseBody
	public Json add(UserVo user) {
		Json json = new Json();
		try {
			this.userService.add(user);
			json.setMsg("添加成功！");
			json.setSuccess(true);
		} catch (Exception e) {
			log.error("添加用户异常。", e);
			json.setMsg("添加失败！");
		}

		return json;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public Json delete(Long id) {
		Json json = new Json();
		try {
			if (Constants.isSuperMan(id)) {
				json.setSuccess(false);
				json.setMsg("删除失败：不能删除超级管理员！");
			} else {
				this.userService.delete(id);
				json.setSuccess(true);
				json.setMsg("删除成功！");
			}

		} catch (Exception e) {
			log.error("删除用户异常。", e);
			json.setMsg("删除失败！");
		}

		return json;
	}

	@RequestMapping("/deleteBatch")
	@ResponseBody
	public Json deleteBatch(String idsString) {
		Json json = new Json();
		try {
			String[] arrId = idsString.split(",");
			List<Long> idList = new LinkedList<>();
			for (int i = 0; i < arrId.length; i++) {
				idList.add(Long.valueOf(arrId[i]));
			}
			if(idList.contains(Constants.SUPER_MAN_NO)){
				json.setSuccess(false);
				json.setMsg("删除失败：删除列表中不能包含超级管理员！");
			}else{
				this.userService.deleteBatch(idList);
				json.setSuccess(true);
				json.setMsg("删除成功！");
			}
		} catch (Exception e) {
			log.error("批量删除异常。", e);
			json.setMsg("删除失败！");
		}

		return json;
	}

	@RequestMapping("/edit")
	@ResponseBody
	public Json edit(UserVo userVo) {
		Json json = new Json();
		try {
			this.userService.edit(userVo);
			json.setSuccess(true);
			json.setMsg("编辑成功！");
		} catch (Exception e) {
			log.error("编译用户异常。", e);
			json.setMsg("编辑失败，用户名已存在！");
		}

		return json;
	}

	@RequestMapping("/getObject")
	@ResponseBody
	public UserVo getObject(Long id) {
		return this.userService.get(id);
	}

	@RequestMapping("/grant")
	@ResponseBody
	public Json grant(UserVo user, @CookieValue(GorgeousParameters.AUTH_COOKIE_NAME) String sid) {
		Json json = new Json();
		try {
			GeneralUserVo guser = CurrentUserHolder.get();
			if (guser == null) {
				guser = this.authorizeResource.cuser(sid);
			}
			List<Long> myRoleIdList = null;
			if (!Constants.isSuperMan(guser.getId())) {
				myRoleIdList = this.userService.myRoleIdList(guser.getId());
				for (ResourceVo r : guser.getPermitResList()) {
					myRoleIdList.add(r.getId());
				}
			}
			this.userService.grant(user, myRoleIdList);
			json.setSuccess(true);
			json.setMsg("授权成功！");
		} catch (Exception e) {
			log.error("授权异常。", e);
			json.setMsg("授权失败！");
		}

		return json;

	}

	@RequestMapping("/grantBatch")
	@ResponseBody
	public Json grantBatch(UserVo user, @CookieValue(GorgeousParameters.AUTH_COOKIE_NAME) String sid) {
		Json json = new Json();
		try {
			GeneralUserVo guser = CurrentUserHolder.get();
			if (guser == null) {
				guser = this.authorizeResource.cuser(sid);
			}
			List<Long> myRoleIdList = null;
			if (guser.getId() != Constants.SUPER_MAN_NO) {
				myRoleIdList = this.userService.myRoleIdList(guser.getId());
				for (ResourceVo r : guser.getPermitResList()) {
					myRoleIdList.add(r.getId());
				}
			}
			this.userService.grantBatch(user, myRoleIdList);
			json.setSuccess(true);
			json.setMsg("授权成功！");
		} catch (Exception e) {
			log.error("授权异常。", e);
			json.setMsg("授权失败！");
		}

		return json;
	}

	@RequestMapping("/editUserInfo")
	@ResponseBody
	public Json editUserInfo(UserVo userVo) {
		Json json = new Json();
		try {
			this.userService.editUserInfo(userVo);
			json.setSuccess(true);
			json.setMsg("修改成功！");
		} catch (Exception e) {
			log.error("编辑用户信息异常。", e);
			json.setMsg("修改失败！");
		}

		return json;
	}

	@RequestMapping("/datagrid")
	@ResponseBody
	public DataGrid<UserVo> datagrid(UserVo user) {
		DataGrid<UserVo> datagrid = new DataGrid<>();
		try {
			Page<UserVo> page = this.userService.pagelist(user);
			datagrid.setTotal(page.getTotalElements());
			datagrid.setRows(page.getContent());
		} catch (Exception e) {
			log.error("查询应用列表异常。", e);
		}

		return datagrid;
	}

	@SecurityNone
	@RequestMapping("/combogrid")
	@ResponseBody
	public List<UserVo> combogrid(UserVo user) {
		try {
			if(user.getQ() == null || user.getQ().isEmpty()){
				return Collections.emptyList();
			}
			user.setUserCode(user.getQ());
			user.setPage(1);
			user.setRows(10);
			Page<UserVo> page = this.userService.pagelist(user);
			return page.getContent();
		} catch (Exception e) {
			log.error("查询应用列表异常。", e);
		}

		return Collections.emptyList();
	}

	@SecurityNone
	@RequestMapping("/myUserInfo")
	public String myUserInfo() {
		return "sys/user/userShow";
	}
	
	@SecurityNone
	@RequestMapping("/verifyOldPasswardPage")
	public ModelAndView verifyOldPasswardPage(@CookieValue(GorgeousParameters.AUTH_COOKIE_NAME) String sid) {
		ModelAndView mv = new ModelAndView("sys/user/userEditPwdVerifyOldPwd");
		GeneralUserVo guser = CurrentUserHolder.get();
		if (guser == null) {
			guser = this.authorizeResource.cuser(sid);
		}
		mv.addObject("guser", guser);
		return mv;
	}
	
	@SecurityNone
	@RequestMapping("/flushNewPasswardPage")
	public ModelAndView flushNewPasswardPage(@CookieValue(GorgeousParameters.AUTH_COOKIE_NAME) String sid) {
		ModelAndView mv = new ModelAndView("sys/user/userEditPwdFlushNewPwd");
		GeneralUserVo guser = CurrentUserHolder.get();
		if (guser == null) {
			guser = this.authorizeResource.cuser(sid);
		}
		mv.addObject("guser", guser);
		return mv;
	}
	
	@SecurityNone
	@RequestMapping("/verifyOldPassward")
	@ResponseBody
	public Json verifyOldPassward(Long id, String oldPassword) {
		Json json = new Json();
		try {
			boolean equal = this.userService.verifyOldPasswardCorrect(id, oldPassword);

			json.setSuccess(equal);
			json.setMsg(equal ? "原密码正确!" : "原密码错误!");
		} catch (Exception e) {
			log.error("系统繁忙，请稍后重试。", e);
			json.setSuccess(false);
			json.setMsg("系统繁忙，请稍后重试。");
		}

		return json;
	}
	
	@SecurityNone
	@RequestMapping("/editPassward")
	@ResponseBody
	public Json editPassward(Long id, String password) {
		Json json = new Json();
		try {
			this.userService.updatePassward(id, password);

			json.setSuccess(true);
			json.setMsg("修改密码成功!");
		} catch (Exception e) {
			log.error("修改密码失败。", e);
			json.setSuccess(false);
			json.setMsg("修改密码失败。");
		}

		return json;
	}

	@SecurityNone
	@RequestMapping("/checkUserCodeUnique")
	@ResponseBody
	public Json checkUserCodeUnique(String userCode) {
		Json json = new Json();
		try {
			boolean unique = this.userService.checkUserCodeUnique(userCode);

			json.setSuccess(unique);
			json.setMsg(unique ? "用户编码唯一!" : "用户编码已存在!");
		} catch (Exception e) {
			log.error("校验用户名唯一性", e);
		}

		return json;
	}

	@SessionNone
	@SecurityNone
	@RequestMapping("/signout")
	@ResponseBody
	public Object signout(HttpServletRequest request, HttpServletResponse response) {
		try {
			Cookie oldtoken = TokenCooikeMaster.getInstunce().remove(request, response);
			if (oldtoken != null) {
				this.authorizeResource.signout(oldtoken.getValue());
			}
		} catch (Exception e) {
			log.error("退出登录异常。", e);
		}

		return new ProcessResult(true, "退出登录成功。");
	}

}
